package inits

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"video/config"
	"video/model"
)

var DB *gorm.DB
var err error

func InitMysql() {
	// refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details
	a := config.Apps.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", a.User, a.Password, a.Host, a.Port, a.Database)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	sqlDB, _ := DB.DB()
	sqlDB.SetMaxIdleConns(10)
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetConnMaxLifetime(0)
	fmt.Println("mysql连接成功")
	err = DB.AutoMigrate(&model.Video{}, &model.User{}, &model.VideoDate{})
	if err != nil {
		panic(err)
	}
	fmt.Println("迁表成功")
}
